<template>
  <div class="page_user_mgr">
    <Row style="margin: 5px 0px 10px 0px;">
      <Select v-model="selTrainCenterId" filterable  :placeholder="$t('common.trainSePlaceTips')" style="width: 200px;margin-right: 20px"
              v-show="isCanChooseTc">
        <Option v-for="tc in trainCenterList" :value="tc.id" :key="tc.id">{{tc.name}}</Option>
      </Select>
      <Input v-model="searchKeyword"   :placeholder="$t('deviceP.phoneOrStudentTips')"  style="width: 200px;margin-right: 20px"/>
      <Button class="btnWhite" type="primary" icon="ios-search" style="margin-right: 20px" @click="search">{{$t('search')}}</Button>
      <Button  class="btnWhite" type="primary" icon="md-add" @click="showAddModal">{{$t('common.addSubBtn')}}</Button>
    </Row>

    <Row class="list_row" style="min-height: 400px;">
      <Table :columns="columns" border :data="userList" stripe :no-data-text="noDataMsg">
        <template slot-scope="{ row, index }" slot="seq">
          {{(currentPage - 1) * pageSize + index + 1}}
        </template>
        <template slot-scope="{ row, index }" slot="roleId">
          <div>
            <span v-if="row.roleId == 1">{{$t('common.sysOpt')}} </span>
            <span v-if="row.roleId == 2">{{$t('common.trainerAd')}} </span>
            <span v-if="row.roleId == 3"> {{$t('common.trainersubAd')}}</span>
            <span v-if="row.roleId == 4">{{$t('coache')}}</span>
            <span v-if="row.roleId == 5">{{$t('common.trainerName')}}</span>
          </div>
        </template>
        <template slot-scope="{ row, index }" slot="trainCenterName">
          <div>
            <span v-if="row.trainCenterList.length >0">{{row.trainCenterList[0].name}}</span>
          </div>
        </template>
      </Table>
      <div class="div_page">
        <Page :total="totalCount" :current="currentPage" :page-size="pageSize"
              show-total show-elevator prev-text="<" next-text=">" @on-change="pageChg"/>
      </div>
    </Row>
    <Modal v-model="entityModelVisiable" :mask-closable="false" width="500" :title="entityModelTitle">
      <Form ref="entityFormRef" :model="entityForm" :rules="entityFormValidateRules" :label-width="120">
        <FormItem :label="$t('common.phone')" prop="phone" v-show="$i18n.locale === 'zh-CN'">
          <Input v-model="entityForm.phone" :placeholder="$t('common.phonePlaceTips')"></Input>
        </FormItem>
        <FormItem :label="$t('common.mail')" prop="mail" v-show="$i18n.locale === 'en-US'">
          <Input v-model="entityForm.mail"  :placeholder="$t('common.emailPlaceTips')"></Input>
        </FormItem>
        <FormItem :label="$t('common.realName')"   prop="nickName">
          <Input v-model="entityForm.nickName" :placeholder="$t('common.realNameTips')" ></Input>
        </FormItem>
        <FormItem :label="$t('common.password')"  prop="password" v-show="showPwdInput">
          <Input v-model="entityForm.password" type="password" icon="md-lock"   :placeholder="$t('common.passwordPlaceTips')"></Input>
        </FormItem>

        <FormItem :label="$t('loginL.confirmPwd')" prop="confirmPassword" v-show="showPwdInput">
          <Input v-model="entityForm.confirmPassword" type="password" icon="md-lock" :placeholder="$t('loginL.pwdConfirmPlaceTips')"></Input>
        </FormItem>
      </Form>
      <div slot="footer" style="text-align: center">
        <Button @click="entityModelVisiable=false">{{$t('cancel')}}</Button>
        <Button type="primary" @click="saveOrUpdate" :loading="saveLoading" style="margin-left: 15px">
          <span v-if="!saveLoading">{{$t('save')}}</span>
          <span v-else>{{$t('save')}}....</span>
        </Button>
      </div>
    </Modal>
    <Modal v-model="pwdModalVisiable" :mask-closable="false" width="500" :title="$t('common.resetPassword')">
      <Form ref="pwdFormRef" :model="pwdForm" :rules="changePwdValidateRules" :label-width="80">
        <FormItem :label="$t('loginL.pwd')" pwd prop="password">
          <Input v-model="pwdForm.password" type="password" icon="md-lock"   :placeholder="$t('loginL.pwdNewPlaceTips')" ></Input>
        </FormItem>
        <FormItem :label="$t('loginL.confirmPwd')" prop="confirmPassword">
          <Input v-model="pwdForm.confirmPassword" type="password" icon="md-lock" :placeholder="$t('loginL.pwdConfirmPlaceTips')"></Input>
        </FormItem>
      </Form>
      <div slot="footer" style="text-align: center">
        <Button @click="pwdModalVisiable=false">{{$t('cancel')}}</Button>
        <Button type="primary" @click="changePwd" :loading="pwdLoading" style="margin-left: 15px">
          <span v-if="!pwdLoading">{{$t('save')}}</span>
          <span v-else>{{$t('save')}}....</span>
        </Button>
      </div>
    </Modal>

    <Modal v-model="funcModalVisiable" :mask-closable="false" width="500" :title= "$t('common.setPower')" >
      <Tree :data="menuTreeData" show-checkbox ref="menuTree"></Tree>
      <div slot="footer" style="text-align: center">
        <Button @click="funcModalVisiable=false">{{$t('cancel')}}</Button>
        <Button type="primary" @click="saveFunc" :loading="funcLoading" style="margin-left: 15px">
          <span v-if="!funcLoading">{{$t('save')}}</span>
          <span v-else>{{$t('save')}}....</span>
        </Button>
      </div>
    </Modal>

  </div>
</template>

<script>
import SubAdminApi from '@/api/subAdminApi'
import { isEmpty, copyObj } from '@/libs/util'
import TrainCenterApi from '@/api/trainCenterApi'

export default {
  name: 'sub-admin-mgr',
  data () {
    const validatePassCheck = (rule, value, callback) => {
      if (value !== this.entityForm.password) {
        callback(new Error( this.$t('common.pwd2Diff')))
      } else {
        callback()
      }
    }
    const validateChangePassCheck = (rule, value, callback) => {
      if (value !== this.pwdForm.password) {
        callback(new Error( this.$t('common.pwd2Diff')))
      } else {
        callback()
      }
    }

    return {
      selSubAdminId: '',
      funcLoading: false,
      funcModalVisiable: false,
      menuTreeData: [],
      selTrainCenterId: '',
      isCanChooseTc: false,
      noDataMsg: this.$t('common.noData'),
      trainCenterLoading: false,
      trainCenterList: [],
      searchKeyword: '',
      entityModelTitle: this.$t('common.addSubBtn'),
      showPwdInput: true,
      currentPage: 1,
      totalCount: null,
      pageSize: 10,
      saveLoading: false,
      pwdLoading: false,
      entityModelVisiable: false,
      pwdModalVisiable: false,
      entityForm: {
        id: '',
        nickName: '',
        phone: '',
        mail:'',
        password: '',
        confirmPassword: '',
        trainCenterId: ''
      },
      changePwdValidateRules: {
        password: [
          { required: true, message: this.$t('common.passwordMustTips') , trigger: 'blur' },
          { type: 'string', min: 6, max: 18, message: this.$t('common.password6and8') , trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: this.$t('loginL.pwdConfirmPlaceTips'), trigger: 'blur' },
          { validator: validateChangePassCheck, trigger: 'blur' }
        ]
      },
      changePwdUserId: '',
      pwdForm: {
        password: '',
        confirmPassword: ''
      },
      entityFormValidateRules: {
        nickName: [
          { required: true, message:this.$t('common.nameMustTips'), trigger: 'blur' },
          // {type: 'string', pattern: '^[\u4E00-\u9FA5]{2,6}$', message: '姓名必须是长度必须2-6位的中文', trigger: 'blur'}
          { type: 'string', min: 2, max: 32, message: this.$t('common.name2and32'),  trigger: 'blur' }

        ],
        phone: [
          { required: this.$i18n.locale === 'zh-CN' ? true : false, message: this.$t('common.phoneMustTips'), trigger: 'blur' },
          { type: 'string', pattern: '^[1][3-9][0-9]{9}$', message: this.$t('common.phoneFormate'), trigger: 'blur' }
        ],
        mail: [
        {
            required:  this.$i18n.locale === 'zh-CN' ? false : true,
            message: this.$t("common.emailMust"),
            trigger: "blur",
          },
          {
            type: "string",
            pattern: "^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$",
            message: this.$t("common.emailFormate"),
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message:  this.$t('common.passwordMustTips '), trigger: 'blur' },
          { type: 'string', min: 6, max: 18, message:  this.$t('common.password6and8'), trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message:  this.$t('common.confirmPasswordMustTips '),trigger: 'blur' },
          { validator: validatePassCheck, trigger: 'blur' }
        ]
      },
      userList: [],
      columns: [
        {
          title: this.$t('common.seq'), 
          slot: "seq",
          width: '110',
          render: (h, params) => {
            return h('span', {
              class: 'sortBlock'
            }, params.index + 1)
          }
        },
        { 
          title: this.$t('common.name'), 
          key: 'nickName'
        },
        {
          title: this.$i18n.locale === 'zh-CN' ? this.$t('common.phone') : this.$t('common.mail'), 
          key: this.$i18n.locale === 'zh-CN' ? "phone" : "mail",
        },
        { 
          title: this.$t('common.roleName'), 
          slot: 'roleId'
        },
        {
          title: this.$t('common.createTime'), 
          key: 'createTime'
        },
        {
          title: this.$t('common.optColumn'), 
          key: 'action',
          width: 410,
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'warning',
                  size: 'small'
                },
                class: 'btnBlue',
                style: {
                  marginRight: '15px'
                },
                on: {
                  click: () => {
                    this.showEditModal(params.row)
                  }
                }
              }, this.$t('common.editBtn')),
              h('Button', {
                props: {
                  type: 'warning',
                  size: 'small'
                },
                style: {
                  marginRight: '15px'
                },
                class: 'btnYellow',
                on: {
                  click: () => {
                    this.showResetPwd(params.row.id)
                  }
                }
              }, this.$t('common.resetPassword')),
              h('Button', {
                props: {
                  type: 'warning',
                  size: 'small'
                },
                style: {
                  marginRight: '15px'
                },
                class: 'greenYellow',
                on: {
                  click: () => {
                    this.showAssignFuncModal(params.row.id)
                  }
                }
              },  this.$t('common.assignPowerBtn')),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {},
                class: 'btnRed',
                on: {
                  click: () => {
                    this.delUser(params.row)
                  }
                }
              }, this.$t('common.deleteBtn'))
            ])
          }
        }
      ]
    }
  },
  mounted () {
    this.initFunc()
  },
  methods: {
    initFunc () {
      TrainCenterApi.userTrainCenterScope().then(res => {
        const data = res.data.data
        if (data.canSelect == '1') {
          this.isCanChooseTc = true
          this.trainCenterList = data.list
          if (this.trainCenterList.length > 0) {
            this.selTrainCenterId = this.trainCenterList[0].id
          }
        } else {
          this.selTrainCenterId = data.trainCenterId
        }
        this.search()
      }, error => {
        this.$Message.error(error.response.data.msg)
      })
    },
    pageChg (selPage) {
      this.currentPage = selPage
      this.fetchUserList()
    },
    search () {
      this.currentPage = 1
      this.fetchUserList()
    },
    fetchUserList () {
      this.noDataMsg = this.$t('common.loading');
      this.userList = []
      var param = { 'pageSize': this.pageSize, 'currentPage': this.currentPage }
      if (this.searchKeyword.length > 0) {
        param.nickName = this.searchKeyword
      }
      SubAdminApi.pageResult(this.selTrainCenterId, param).then(res => {
        this.noDataMsg = this.$t('common.noData');
        this.userList = res.data.data.pageResult.items
        this.totalCount = res.data.data.pageResult.totalCount
      }, error => {
        this.$Message.error(error.response.data.msg)
      })
    },
    saveOrUpdate () {
      this.$refs.entityFormRef.validate((valid) => {
        if (valid) {
          this.saveLoading = true
          if( this.$i18n.locale === 'zh-CN' ){
            SubAdminApi.saveOrUpdate(this.entityForm).then(response => {
            this.saveLoading = false
            this.$Message.success(this.$t('common.optSuc') )
            this.$refs.entityFormRef.resetFields()
            this.entityModelVisiable = false
            this.fetchUserList()
          }, error => {
            this.saveLoading = false
            this.$Message.error(error.response.data.msg)
          })
          }else{
            SubAdminApi.saveOrUpdateMail(this.entityForm).then(response => {
            this.saveLoading = false
            this.$Message.success(this.$t('common.optSuc') )
            this.$refs.entityFormRef.resetFields()
            this.entityModelVisiable = false
            this.fetchUserList()
          }, error => {
            this.saveLoading = false
            this.$Message.error(error.response.data.msg)
          })
          }
        
        }
      })
    },
    delUser (user) {
      this.$Modal.confirm({
        title:this.$t('common.dDeleteTitleConfirm'),
        content:  this.$t('common.DdeleteCt'),
        okText: this.$t('common.deleteBtn'),
        cancelText: this.$t('cancel'),
        onOk: () => {
          this.doDel(user.id)
        }
      })
    },
    doDel (id) {
      SubAdminApi.delete(id).then(res => {
        this.$Message.success(this.$t('common.deleteSuc'))
        this.fetchUserList()
      }, error => {
        this.$Message.error(error.response.data.msg)
      })
    },
    showResetPwd (id) {
      this.$refs.pwdFormRef.resetFields()
      this.changePwdUserId = id
      this.pwdModalVisiable = true
    },
    changePwd () {
      this.$refs.pwdFormRef.validate((valid) => {
        if (valid) {
          this.pwdLoading = true
          SubAdminApi.resetPwd(this.changePwdUserId, this.pwdForm.password, this.pwdForm.confirmPassword).then(response => {
            this.pwdLoading = false
            this.$Message.success(this.$t('common.pwdSuc') )
            this.$refs.entityFormRef.resetFields()
            this.pwdModalVisiable = false
          }, error => {
            this.pwdLoading = false
            this.message = error.response.data.msg
          })
        }
      })
    },
    showAddModal () {
      this.$refs.entityFormRef.resetFields()
      this.entityModelVisiable = true
      this.showPwdInput = true
      this.entityModelTitle = this.$t('common.addSubBtn')
      this.entityForm = {
        id: '',
        userName: '',
        nickName: '',
        phone: '',
        mail:'',
        roleId: '2',
        password: '',
        confirmPassword: '',
        trainCenterId: this.selTrainCenterId
      }
    },
    showEditModal (row) {
      this.$refs.entityFormRef.resetFields()
      this.entityModelVisiable = true
      this.entityModelTitle = this.$t('common.editBtn')
      this.showPwdInput = false
      this.entityForm = copyObj(row)
      this.entityForm.trainCenterId = this.selTrainCenterId
      this.entityForm.password = '******'
      this.entityForm.confirmPassword = '******'
    },
    showAssignFuncModal (id) {
      this.funcModalVisiable = true
      this.menuTreeData = []
      this.selSubAdminId = id
      SubAdminApi.getMenuTreeData(id).then(res => {
        this.menuTreeData = res.data.data
      }, error => {
        this.$Message.error(error.response.data.msg)
      })
    },
    saveFunc () {
      const nodes = this.$refs.menuTree.getCheckedNodes()
      if (nodes.length == 0) { 
        this.$Message.warning(this.$t('common.menuSelTips'))
        return
      }
      var menuIdArr = []
      for (var i = 0; i < nodes.length; i++) {
        menuIdArr.push(nodes[i].id)
      }
      this.$Spin.show()
      SubAdminApi.saveMenuTreeData(this.selSubAdminId, menuIdArr.join(',')).then(res => {
        this.$Spin.hide()
        this.funcModalVisiable = false
        this.$Message.success( this.$t('common.optSuc') )
      }, error => {
        this.$Spin.hide()
        this.$Message.error(error.response.data.msg)
      })
    }

  }
}
</script>
